<template>
  <div class="login-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="80px"
      class="ruleForm"
    >
      <h2>后台管理系统</h2>

      <el-form-item label="账号：" prop="userName">
        <el-input v-model="ruleForm.userName" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          class="loginBtn"
          type="primary"
          @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
        <el-button class="loginBtn" @click="resetForm(ruleFormRef)"
          >Reset</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { LoginData } from "../type/login";
import type { FormInstance } from "element-plus";
import Api from "../request/api";
import { useRouter } from "vue-router";

const router = useRouter();
const ruleForm = reactive(new LoginData().ruleForm);
const rules = {
  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 3, max: 10, message: "账号的长度在3-10之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 10, message: "密码的长度在3-10之间", trigger: "blur" },
  ],
};

const ruleFormRef = ref<FormInstance>();
// 登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 对表单内容进行验证
  // valid为布尔类型
  formEl.validate((valid) => {
    if (valid) {
      Api.login(ruleForm).then((res: { data: { token: string } }) => {
        // 保存token
        localStorage.setItem("token", res.data.token);
        // 跳转页面
        router.push("/");
      });
      console.log("submit!");
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  background: url("https://ycpg-setting.oss-cn-hangzhou.aliyuncs.com/image/bj.png");
  padding: 0.1px;
  .ruleForm {
    width: 500px;
    margin: 200px auto;
    background-color: #fff;
    padding: 30px;
    border-radius: 20px;
  }
  .loginBtn {
    width: 48%;
  }
  h2 {
    margin-bottom: 20px;
  }
}
</style>
